package kvoog.arkanoid.core;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Mapper;
import com.artemis.systems.EntityProcessingSystem;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;

public class InputSystem extends EntityProcessingSystem implements
		InputProcessor {

	@Mapper private ComponentMapper<KeyInputReceiver> kim;

	private Map<Integer,Integer> keysDown = new HashMap<Integer,Integer>();

	@SuppressWarnings("unchecked")
	public InputSystem() {
		super(Aspect.getAspectForAll(KeyInputReceiver.class));
	}

	@Override
	protected void initialize() {
		super.initialize();
		Gdx.input.setInputProcessor(this);
	}

	@Override
	public boolean keyDown(int keycode) {

		if (keysDown.get(keycode) != null)
			keysDown.put(keycode, keysDown.get(keycode)+1);
		else
			keysDown.put(keycode, 1);	
		return true;
	}

	@Override
	public boolean keyUp(int keycode) {
		
		keysDown.remove(keycode);
		return true;
	}

	@Override
	public boolean keyTyped(char character) {

		return false;
	}

	@Override
	public boolean touchDown(int screenX, int screenY, int pointer, int button) {

		return false;
	}

	@Override
	public boolean touchUp(int screenX, int screenY, int pointer, int button) {

		return false;
	}

	@Override
	public boolean touchDragged(int screenX, int screenY, int pointer) {

		return false;
	}

	@Override
	public boolean mouseMoved(int screenX, int screenY) {

		return false;
	}

	@Override
	public boolean scrolled(int amount) {

		return false;
	}

	@Override
	protected void process(Entity e) {
		
		KeyInputReceiver kiRec = kim.get(e);
		Set<String> keys = kiRec.keyMapping.keySet();
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = it.next();
			KeyInputReceiver.KeyInputData kiData = kiRec.keyMapping.get(key);
			if (keysDown.get(kiData.keycode) != null) {
				if (kiData.toggle) {
					if (keysDown.get(kiData.keycode) == 1)
						kiData.pressed = true;
					else
						kiData.pressed = false;
				}
				else
					kiData.pressed = true;
			}
			else
				kiData.pressed = false;
		}
	}
}
